import { Stack } from "expo-router";
import { ThemeProvider } from "@/contexts/ThemeContext";
import * as SplashScreen from "expo-splash-screen";
import { useEffect } from "react";
import { Platform } from "react-native";
import { ErrorBoundary } from "./error-boundary";
import { StatusBar } from "expo-status-bar";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useTheme } from "@/hooks/useTheme";
import Colors from "@/constants/colors";
import { useFonts } from 'expo-font';
import { FontAwesome } from '@expo/vector-icons';

export const unstable_settings = {
  initialRouteName: "tabs",
};

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

export default function RootLayout() {
  const [loaded, error] = useFonts({
    ...FontAwesome.font,
  });

  useEffect(() => {
    if (error) {
      console.error(error);
      throw error;
    }
  }, [error]);

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }

  return (
    <ThemeProvider>
      <ErrorBoundary>
        <SafeAreaProvider>
          <RootLayoutNav />
        </SafeAreaProvider>
      </ErrorBoundary>
    </ThemeProvider>
  );
}

/**
 * 根布局导航函数
 *
 * @returns 返回根布局导航组件
 */
function RootLayoutNav() {
  const { colors } = useTheme();
  
  return (
      <Stack
        screenOptions={{
          headerStyle: {
            backgroundColor: colors.background,
          },
          headerTintColor: colors.text,
          contentStyle: {
            backgroundColor: colors.background,
          },
          headerShown: false
        }}
      >
        <Stack.Screen name="tabs" options={{ headerShown: false }} />
        <Stack.Screen name="category/[id]" options={{ headerShown: true }} />
        <Stack.Screen name="question/[id]" options={{ headerShown: true }} />
        <Stack.Screen
          name="simulation/start"
          options={{
            headerShown: true,
            headerBackVisible: false,
          }}
        />
        <Stack.Screen
          name="simulation/question"
          options={{
            headerShown: true,
            headerBackVisible: false,
          }}
        />
        <Stack.Screen
          name="simulation/results"
          options={{
            headerShown: true,
            headerBackVisible: false,
          }}
        />
      </Stack>
  );
}
